package com.ruoyi.coal.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.thread.ThreadUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.net.InetSocketAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger log = LoggerFactory.getLogger(com.ruoyi.coal.common.utils.NettyServerHandler.class);

    public static ChannelGroup channelGroup = (ChannelGroup)new DefaultChannelGroup((EventExecutor)GlobalEventExecutor.INSTANCE);

    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            ThreadUtil.execAsync(() -> System.out.println("收到客户消息"+ msg.toString()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void channelReadComplete(ChannelHandlerContext ctx) {
        if (BeanUtil.isNotEmpty(ctx, new String[0]))
            ctx.flush();
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        channelGroup.add(ctx.channel());
        log.info("客户端与服务端建立连接:{}", getClientIp(ctx));
    }

    public void channelInactive(ChannelHandlerContext ctx) {
        try {
            super.channelInactive(ctx);
            log.info("客户端与服务端断连:{}", getClientIp(ctx));
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            ctx.close();
        }
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (BeanUtil.isNotEmpty(ctx, new String[0])) {
            ctx.close();
            log.error("连接异常，服务端主动与 " + getClientIp(ctx) + " 断开连接{}");
            System.out.println(cause.getMessage());
        }
    }

    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        try {
            log.error("服务端读取超时：{}", getClientIp(ctx));
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            if (BeanUtil.isNotEmpty(ctx, new String[0]))
                ctx.close();
        }
    }

    private String getClientIp(ChannelHandlerContext ctx) {
        InetSocketAddress insocket = (InetSocketAddress)ctx.channel().remoteAddress();
        return insocket.getAddress().getHostAddress();
    }

    private int getClientPort(ChannelHandlerContext ctx) {
        InetSocketAddress insocket = (InetSocketAddress)ctx.channel().remoteAddress();
        return insocket.getPort();
    }
}
